var mqtt = require('mqtt');

var async = require("async");
console.log('Connecting to: %s using access token: %s', process.env.THINGSBOARD_HOST, process.env.ACCESS_TOKEN);

var client  = mqtt.connect('mqtt://'+ process.env.THINGSBOARD_HOST,{
    username: process.env.ACCESS_TOKEN
});


function sleep(ms) {
    return new Promise(resolve=>setTimeout(resolve, ms))
}


function randomNum(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
            break; 
    } 
}

async function send(client,callback){
     let telemetry = JSON.parse(process.env.TELEMETRY)
   
    for (i = 0; i < 1; i++) {
       let temperature = randomNum(0,55);
       telemetry.temperature = temperature;
       console.log(JSON.stringify(telemetry))
       client.publish('v1/devices/me/telemetry', JSON.stringify(telemetry));
       console.log('Telemetry published!');
       await sleep(1000)
    }
    //callback(null,client)
}

function closeClinet(client,callback){
 console.log("close clinet");
 client.end();
 console.log("close clinet successful");
}

client.on('connect', function () {
    console.log('Client connected!');
    console.log(process.env.TELEMETRY)
    client.publish('v1/devices/me/attributes', process.env.ATTRIBUTES);
    console.log('Attributes published!');
    client.publish('v1/devices/me/telemetry', process.env.TELEMETRY);
    async.waterfall([async.constant(client),send,async.constant(client),closeClinet]);
   
});
